package org.yang.snake.util;

import lombok.experimental.UtilityClass;
import org.yang.snake.vo.MenuTreeVO;

import java.util.ArrayList;
import java.util.List;

/**
 * 建树工具类
 * 从别处抄过来的
 * @author other
 */
@UtilityClass
public class TreeUtil {

    /**
     * 两层循环实现建树
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public List<MenuTreeVO> buildByLoop(List<MenuTreeVO> treeNodes, Long root) {

        List<MenuTreeVO> trees = new ArrayList<>();

        for (MenuTreeVO treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add(treeNode);
            }

            for (MenuTreeVO it : treeNodes) {
                if (it.getParentId().equals(treeNode.getId()) ) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<>());
                    }
                    treeNode.getChildren().add(it);
                }
            }
        }
        return trees;
    }
}
